<?php

namespace App\Http\Controllers\OperationManagement;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

/**
 * @group 环卫->垃圾点位路径规划
 *
 * 采用 restful api
 *
 * Body Parameters 表示请求的所需要的参数
 *
 * Query Parameters 表示返回参数的名称
 */
class TrashPathController extends Controller
{
    /**
     *@bodyParam nums int optional 规划线路数量
     */
    public function index(Request $request)
    {

        $validator = Validator::make($request->all(),genValidate());
        if($validator->fails()){
            return response()->json(encodeMsg($validator->errors()->messages(),400),400);
        }
        $nums = (string) $request->input('nums',1);
        $path = base_path("final" . DIRECTORY_SEPARATOR . "main.py");
        $host = $request->getHttpHost();

        if ($host != "118.24.143.118:8001") {
            $res = $this->req(['nums'=>$nums],"http://118.24.143.118:8001/api/algorithm/path");
            return \response($res);
        }

        $res = exec("python3 {$path} -n {$nums}");

        return response()->json(encodeMsg(array_values((array) json_decode($res)), 200), 200);
    }

    public function req($data, $url)
    {
        $options = array(
            "http" => array(
                "method" => "GET",
                "timeout" => 60 // 超时时间（单位:s）
            )
        );
        $param = "";
        foreach ($data as $k => $v) {
            $param .= $k . "=" . $v . "&";
        }
        $param = substr($param, 0, strlen($param) - 1);
        $url = "$url?$param";
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }
}
